package com.practice.matrix;

public class Spiral {
	public static void main(String[] args) {
		Spiral s = new Spiral();
		s.printSpiral(1, 1);
		s.printSpiral(5, 5);
		s.printSpiral(6, 6);
		s.printSpiral(7, 8);
		s.printSpiral(8, 7);
	}
	
	private void printSpiral(int M, int N) {
		int[][] a = new int[M][N];
		fill(a, M, N, 0, 1);
		for (int i=0; i<M; i++) {
			for (int j=0; j<N; j++) {
				System.out.print(String.format("%-5d", a[i][j]));
			}
			System.out.println();	
		}
		System.out.println();
	}
	
	private void fill(int[][] a, int M, int N, int k, int n) {
		if (M==0 || N==0) return;
		
		if (M==1) {
			for (int i=0; i<N; i++, n++) a[k][k+i] = n;
			return;
		}
		
		if (N==1) {
			for (int i=0; i<M; i++, n++) a[k+i][k] = n;
			return;
		}
		
		for (int i=0; i<N; i++, n++) a[k][k+i] = n;			// top
		for (int i=1; i<M; i++, n++) a[k+i][k+N-1] = n;		// right
		for (int i=N-2; i>0; i--, n++) a[k+M-1][k+i] = n;	// bottom
		for (int i=M-1; i>0; i--, n++) a[k+i][k] = n; 		// left
		
		fill(a, M-2, N-2, k+1, n);
	}
}
